﻿
using Essensoft.Paylink.WeChatPay;
using Furion.DependencyInjection;
using Furion.DynamicApiController;
using Furion.FriendlyException;
using HiSport.Application.Service.Transaction.Pay.Service;
using HiSport.Application.Service.Transaction.TransactionConfig.Dtos;
using HiSport.Core.Entity.Transaction;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace HiSport.Application.Service.Transaction.TransactionConfig.Service
{

    /// <summary>
    /// 支付设置
    /// </summary>
    //[ApiDescriptionSettings("交易信息", Tag = "支付配置", SplitCamelCase = false), AllowAnonymous]
    [ApiDescriptionSettings("payManagement", Tag = "TransientService", SplitCamelCase = false), AllowAnonymous]
    public class TransactionConfigService : ITransient, ITransactionConfigService, IDynamicApiController
    {

        private readonly SqlSugarRepository<WeChatPaySetting> _weChatPaySetting;


        public TransactionConfigService(SqlSugarRepository<WeChatPaySetting> weChatPaySetting)
        {
            _weChatPaySetting = weChatPaySetting;
        }

        /// <summary>
        /// 获取支付配置
        /// </summary>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "Get"), HttpGet]
        [DisplayName("获取支付配置")]
        public async Task<PaySettingDto> GetPaySetting()
        {

            var res = new PaySettingDto();
            var weChatPay = await _weChatPaySetting.AsQueryable()
                .Select(x => new WeChatPaySettingDto()
                {
                    Id = x.Id.SelectAll(),
                })
                .FirstAsync();
            res.WeChatPaySetting = weChatPay;
            return res;

        }


        /// <summary>
        /// 编辑支付配置（有就新增 没有就修改）
        /// </summary>
        /// <param name="inputDto"></param>
        /// <returns></returns>
        [ApiDescriptionSettings(Name = "EditPaySetting"), HttpPost]
        [DisplayName("编辑支付配置")]
        public async Task<bool> EditPaySetting(PaySettingCreateOrUpdateDto inputDto)
        {
            var res = false;
            var input = new WeChatPaySetting()
            {
                APIv3Key = inputDto.WeChatPaySetting.APIv3Key,
                APIKey = inputDto.WeChatPaySetting.APIKey,
                AppId = inputDto.WeChatPaySetting.AppId,
                Certificate = inputDto.WeChatPaySetting.Certificate,
                MchId = inputDto.WeChatPaySetting.MchId,
                SubMchId = inputDto.WeChatPaySetting.MchId,
                MchIP = inputDto.WeChatPaySetting.MchIP,
            };
            if (inputDto.WeChatPaySetting != null)
            {
                //新增
                if (inputDto.WeChatPaySetting.Id != 0)
                {
                    var weChatPaySetting = await _weChatPaySetting.AsQueryable().FirstAsync(x => x.Id == inputDto.WeChatPaySetting.Id);
                    if (weChatPaySetting != null)
                    {
                        input.Id = weChatPaySetting.Id;
                    }
                }
            }

            if (input.Id == 0)
            {
                res = await _weChatPaySetting.InsertAsync(input);
            }
            else
            {
                res = await _weChatPaySetting.UpdateAsync(input);
            }

            if (!res)
            {
                throw Oops.Oh("编辑失败");
            }
            return res;
        }

        /// <summary>
        /// 获取默认的支付配置（有就用自身的 没有就平台的）
        /// </summary>
        /// <returns></returns>
        public async Task<PayConfig> GetDefaultPaySetting()
        {
            var res = new PayConfig();
            //获取租户的
            var weChatPay = await _weChatPaySetting.AsQueryable()
                .Select(x => new WeChatPayOptions()
                {
                    APIKey = x.APIKey,
                    AppId = x.AppId,
                    Certificate = x.Certificate,
                    MchId = x.MchId,
                    SubMchId = x.SubMchId,
                    RsaPublicKey = "",
                    SubAppId = "",
                    CertificatePassword = "",
                    AppSecret = "",
                    APIv3Key = x.APIv3Key,
                    APIPrivateKey = "",
                })
                .FirstAsync();
            if (weChatPay != null)
            {
                res.WeChatPay = weChatPay;
            }
            else
            {
                try
                {
                    //获取平台的
                    var v = await _weChatPaySetting.AsQueryable()
                        .ClearFilter()
                        .Where(x => x.IsDelete == false && x.TenantId == 0)
                        .Select(x => new WeChatPaySetting()
                        {
                            APIKey = x.APIKey,
                            AppId = x.AppId,
                            Certificate = x.Certificate,
                            MchId = x.MchId,
                            SubMchId = x.SubMchId,
                            // RsaPublicKey = "",
                            // SubAppId = "",
                            // CertificatePassword = "",
                            //  AppSecret = "",
                            APIv3Key = x.APIv3Key,
                            // APIPrivateKey = "",
                        })
                        .FirstAsync();
                    weChatPay = new WeChatPayOptions();
                    weChatPay.APIKey = v.APIKey;
                    weChatPay.AppId = v.AppId;
                    weChatPay.Certificate = v.Certificate;
                    weChatPay.MchId = v.MchId;
                    weChatPay.SubMchId = v.SubMchId;
                    weChatPay.APIv3Key = v.APIv3Key;
                }
                catch (Exception e)
                {
                    throw;
                }




                res.WeChatPay = weChatPay;
            }

            return res;
        }
    }
}
